package com.gitee.cashzhang27.test.sdk.bestsign.core;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.gitee.cashzhang27.test.sdk.bestsign.core.util.CryptUtils;
import com.gitee.cashzhang27.test.sdk.bestsign.domain.AbstractBestSignResponse;
import com.gitee.cashzhang27.test.sdk.bestsign.domain.BestSignRequest;
import com.gitee.cashzhang27.test.sdk.bestsign.domain.DefaultBestSignResponse;
import com.gitee.cashzhang27.test.sdk.bestsign.domain.DownloadBestSignResponse;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/08/13 11:23
 */
@Slf4j
public class DownloadBestSignClient extends AbstractBestSignClient {

  @Override
  public <T extends AbstractBestSignResponse> T execute(BestSignRequest<T> request)
      throws Exception {

    Stopwatch stopwatch = Stopwatch.createStarted();
    String privateKey = request.getPrivateKey();
    String developerId = request.getDeveloperId();
    String serverHost = request.getServerHost();
    String rtick = CryptUtils.getRtick();
    Method methodType = request.getMethodType();
    String methodName = request.getMethodName();
    HttpResponse httpResponse = null;
    request.clearImportantParams();

    if (Method.GET.equals(methodType)) {
      String url = beforeGetMethod(request, privateKey, developerId, serverHost, rtick, methodType,
          methodName);

      httpResponse = HttpUtil.createGet(url).execute();
    }
    if (httpResponse == null) {
      throw new RuntimeException("occur a exception because best sign return null.");
    }
    byte[] bytes = httpResponse.bodyBytes();
    String body = httpResponse.body();
    if (JSONUtil.isJson(body)) {
      DefaultBestSignResponse defaultBestSignResponse = JSONUtil
          .toBean(body, DefaultBestSignResponse.class);
      throw new RuntimeException(
          "errno：" + defaultBestSignResponse.getErrno() + ",errmsg：" + defaultBestSignResponse
              .getErrmsg());
    }
    String base64Str = Base64.encode(bytes);
    DownloadBestSignResponse downloadBestSignResponse = new DownloadBestSignResponse();
    downloadBestSignResponse.setBase64Str(base64Str);
    String jsonStr = JSONUtil.toJsonStr(downloadBestSignResponse);
    Class<T> responseClass = request.getResponseClass();
    log.info(
        "the method executed successfully, taking [{}].",
        stopwatch.stop().toString());
    return JSONUtil.toBean(jsonStr, responseClass);
  }

}
